<template>
  <el-container>
    <el-header>
      <el-upload
        :on-change="handleChange"
        :before-upload="
          () => {
            return false;
          }
        "
      >
        <el-button type="primary" class="button1">选择文件</el-button>
      </el-upload>

      <el-button type="primary" @click="exportExcel" class="button2">导出 Excel</el-button>
      <el-upload
        :on-change="importData"
        :before-upload="
          () => {
            return false;
          }
        "
      >
        <el-button type="primary" class="button1">导入出勤统计</el-button>
      </el-upload>
      <!-- <button @click="exportClick" class="button2">一键导出</button> -->
    </el-header>
    <div class="tab-box">
      <!-- 导入异常事件 -->
      <el-dialog v-model="dialogVisible" title="Tips" width="50%" :before-close="handleClose">
        <!-- <el-table :data="Attendance" style="width: 100%">
          <el-table-column v-for="(k, v) in Attendance[0]" :key="k" :prop="v" :label="v"> </el-table-column>
       -->
        <el-table :data="unArr" style="width: 100%">
          <el-table-column fixed prop="id" label="id" width="150" />
          <el-table-column prop="姓名" label="姓名" width="120" />
          <el-table-column prop="部门" label="部门" width="120" />
          <el-table-column prop="职位" label="职位" width="120" />
          <el-table-column prop="应出勤" label="应出勤" width="120" />
          <el-table-column label="实际出勤" width="120">
            <template #default="{ row }">
              <span>{{
                Number(row["1号"]) +
                Number(row["2号"]) +
                Number(row["3号"]) +
                Number(row["4号"]) +
                Number(row["5号"]) +
                Number(row["6号"]) +
                Number(row["7号"]) +
                Number(row["8号"]) +
                Number(row["9号"]) +
                Number(row["10号"]) +
                Number(row["11号"]) +
                Number(row["12号"]) +
                Number(row["13号"]) +
                Number(row["14号"]) +
                Number(row["15号"]) +
                Number(row["16号"]) +
                Number(row["17号"]) +
                Number(row["18号"]) +
                Number(row["19号"]) +
                Number(row["20号"]) +
                Number(row["21号"]) +
                Number(row["22号"]) +
                Number(row["23号"]) +
                Number(row["24号"]) +
                Number(row["25号"]) +
                Number(row["26号"]) +
                Number(row["27号"]) +
                Number(row["28号"]) +
                Number(row["29号"]) +
                Number(row["30号"]) +
                Number(row["31号"])
              }}</span>
            </template>
          </el-table-column>
          <el-table-column label="出勤时间" width="120">
            <template #default="{ row }">
              <span>{{
                Number(row["1号"]) +
                Number(row["2号"]) +
                Number(row["3号"]) +
                Number(row["4号"]) +
                Number(row["5号"]) +
                Number(row["6号"]) +
                Number(row["7号"]) +
                Number(row["8号"]) +
                Number(row["9号"]) +
                Number(row["10号"]) +
                Number(row["11号"]) +
                Number(row["12号"]) +
                Number(row["13号"]) +
                Number(row["14号"]) +
                Number(row["15号"]) +
                Number(row["16号"]) +
                Number(row["17号"]) +
                Number(row["18号"]) +
                Number(row["19号"]) +
                Number(row["20号"]) +
                Number(row["21号"]) +
                Number(row["22号"]) +
                Number(row["23号"]) +
                Number(row["24号"]) +
                Number(row["25号"]) +
                Number(row["26号"]) +
                Number(row["27号"]) +
                Number(row["28号"]) +
                Number(row["29号"]) +
                Number(row["30号"]) +
                Number(row["31号"]) -
                Number(row["应出勤"])
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="1号" label="1号" width="120" />
          <el-table-column prop="2号" label="2号" width="120" />
          <el-table-column prop="3号" label="3号" width="120" />
          <el-table-column prop="4号" label="4号" width="120" />
          <el-table-column prop="5号" label="5号" width="120" />
          <el-table-column prop="6号" label="6号" width="120" />
          <el-table-column prop="7号" label="7号" width="120" />
          <el-table-column prop="8号" label="8号" width="120" />
          <el-table-column prop="9号" label="9号" width="120" />
          <el-table-column prop="10号" label="10号" width="120" />
          <el-table-column prop="11号" label="11号" width="120" />
          <el-table-column prop="12号" label="12号" width="120" />
          <el-table-column prop="13号" label="13号" width="120" />
          <el-table-column prop="14号" label="14号" width="120" />
          <el-table-column prop="15号" label="15号" width="120" />
          <el-table-column prop="16号" label="16号" width="120" />
          <el-table-column prop="17号" label="17号" width="120" />
          <el-table-column prop="18号" label="18号" width="120" />
          <el-table-column prop="19号" label="19号" width="120" />
          <el-table-column prop="20号" label="20号" width="120" />
          <el-table-column prop="21号" label="21号" width="120" />
          <el-table-column prop="22号" label="22号" width="120" />
          <el-table-column prop="23号" label="23号" width="120" />
          <el-table-column prop="24号" label="24号" width="120" />
          <el-table-column prop="25号" label="25号" width="120" />
          <el-table-column prop="26号" label="26号" width="120" />
          <el-table-column prop="27号" label="27号" width="120" />
          <el-table-column prop="28号" label="28号" width="120" />
          <el-table-column prop="29号" label="29号" width="120" />
          <el-table-column prop="30号" label="30号" width="120" />
          <el-table-column prop="31号" label="31号" width="120" />
        </el-table>
      </el-dialog>

      <el-table
        :data="tableData.list"
        height="100%"
        stripe
        style="width: 100%"
        :row-key="row => row.id"
        :default-expand-all="true"
        @select="selectChange"
        @select-all="selectAllChange"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" :reserve-selection="true" :selectable="handleSelectable" />
        <el-table-column type="expand" width="50px">
          <template #default="{ row }">
            <el-table type="selection" :data="row.work" border show-summary :summary-method="sumMethod" style="width: 100%">
              <el-table-column v-for="(v, i) in tableData.timeHeader" :key="i" :prop="i + ''" :label="v.lable"></el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column v-for="(v, i) in tableData.header" :key="i" :prop="v" :label="v"></el-table-column>
        <el-table-column fixed="right" label="操作">
          <el-button link>操作</el-button>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
    </div>
    <div class="tab-fotter">
      <el-pagination
        small
        background
        layout="total, sizes, prev, pager, next, jumper"
        :current-page="tableData.current"
        :total="tableData.total"
        :default-page-size="tableData.pageSize"
        class="mt-4"
        @size-change="sizeChange"
        @current-change="currentChange"
      />
    </div>
  </el-container>
</template>

<script setup>
import { reactive, ref } from "vue";
import * as XLSX from "xlsx";
import { h } from "vue";
import { ElNotification } from "element-plus";

const dialogVisible = ref(false);
console.log(XLSX);
let importData = uploadFile => {
  let file = uploadFile.raw;

  // 1 cosnt fileReader=  new FileReader()  Web 应用程序异步读取存储在用户计算机上的文件
  let fileReader = new FileReader();

  // 2 读取文件的内容为二进制
  fileReader.readAsBinaryString(file);

  // 3 fileReader.onload 监听读取文件成功
  fileReader.onload = e => {
    // console.log(e.target.result);
    // 二进制文件 xlsx.read(数据，配置项)  插件读取文件 生成工作簿
    let workbook = XLSX.read(e.target.result, {
      type: "binary"
    });
    // console.log(workbook);
    let sheetName = workbook.SheetNames[0];
    let workSheet = workbook.Sheets[sheetName];
    // console.log(workSheet);

    // XLSX.utils.sheet_to_json(工作表) 把工作表转化为json
    let excelDataJson = XLSX.utils.sheet_to_json(workSheet);

    dialogVisible.value = true;
    console.log(excelDataJson, "xx");
    // console.log(excelDataJson);
    for (let i = 0; i < excelDataJson.length; i++) {
      const v = excelDataJson[i];
      Attendance.push(v);
      // Attendance.push(num2);
    }
    const uniqueArr = Array.from(new Set(Attendance.map(JSON.stringify))).map(JSON.parse);
    unArr = uniqueArr;
    console.log(unArr, "测试中");
  };
};
let unArr = [];
let table = [];
const Attendance = [];
const selectAllChange = selection => {
  table = selection;
  console.log("表头全选", selection);
  //处理数据
  //。。。
};

const handleSelectionChange = selection => {
  table = selection;
  console.log(selection);
  //处理数据
  //。。。
  // checked.value = selection.map(item => item.id);
};

const checkAll = ref(false);
const handleSelectable = () => {
  return !checkAll.value;
};
const sumMethod = ({ columns, data }) => {
  columns;
  console.log(columns, "columns");
  console.log(data, "data");
  const department = data["0"][1];
  const name = data["0"][2];
  const id = data["0"][0];
  console.log(department, "部门");
  console.log(name, "姓名");
  console.log(id, "id");
  let arr = [];
  let out = [];
  for (let i = 0; i < tableData.timeHeader.length; i++) {
    // 上班
    const S = data["1"][i];
    // 下班
    const E = data["2"][i];
    const S2 = data["1"][i + 1];
    const D = data["0"][2];
    console.log(D, "部门");
    // console.log(D, "部门");
    // console.log(tableData.header, "测试");
    let hour = 0;
    // hour = tableData.timeHeader[i];
    // let hour2 = 0;
    // console.log(E2, "黑夜");
    // 晚班
    // const E2 = data["1"][i++];
    // console.log(tableData.timeHeader, "测试");
    // console.log(E);
    // 这几个if是啥意思 迟到以及上下班时间 不同部门的 每个部门的时间不一样
    if (S != "" && S != "-" && E != "" && E != "-" && D == "运行工" && S > "08:30" && E > "20:30") {
      // console.log(S, "上班3");
      // console.log(E, "下班3");
      let sTime = new Date("2023-4-26 " + S).getTime();
      // let eTime = new Date("2023-4-26 " + E).getTime();
      let vTime = new Date("2023-4-26 " + "8:30").getTime();
      hour = "迟到" + (vTime - sTime) / 60000 + "分钟";
      // console.log(hour);
      // 运行白班
    } else if (S != "-" && S != "" && E != "-" && E != "" && D == "运行工" && S <= "08:30" && E >= "20:30") {
      console.log(S, "上班go");
      console.log(E, "下班go");
      // console.log("夜班");

      let sTime = new Date("2023-4-26 " + S).getTime();
      let eTime = new Date("2023-4-26 " + E).getTime();
      let min = ((eTime - sTime) / 3600000).toFixed(2);
      // console.log(min, "时间");
      if (min > 12) {
        hour = 12;
        console.log("正");
      } else if (min < 12) {
        const data = isSaveTime(sTime, eTime, 12);
        hour = data.lackTime;
        // console.log(data, "xxxxxxxxxxxx");
      }
      // 运行晚班 // 这个判断对着没 对着呢
    } else if (S == "-" && E != "-" && E != "" && E < "20:30" && D == "运行工") {
      console.log("警告");
      console.log(S2, "下班2");
      console.log(E, "上班2");
      // console.log("夜班");

      let sTime = new Date("2023-4-25 " + E).getTime(); // 上班
      let eTime = new Date("2023-4-26 " + S2).getTime(); // 下班
      // hour = ((eTime - sTime) / 3600000).toFixed(2) + "小时";
      const data = isSaveTime(sTime, eTime, 12);
      hour = data.lackTime;
    } else if (S != "-" && S != "" && E != "-" && E != "" && D == "运行工" && S >= "08:30" && E <= "20:30") {
      console.log(E, "上班5");
      console.log(S2, "下班5");
      // console.log("夜班");

      let sTime = new Date("2023-4-25 " + E).getTime(); // 上班
      let eTime = new Date("2023-4-26 " + S2).getTime(); // 下班
      // let min = ((eTime - sTime) / 3600000).toFixed(2);
      const data = isSaveTime(sTime, eTime, 12);
      hour = data.lackTime;
    } else if (S != "" && S != "-" && E != "" && E != "-" && D == "运行工" && E > "20:30") {
      let sTime = new Date("2023-4-26 " + S).getTime();
      let eTime = new Date("2023-4-26 " + E).getTime();
      let vTime = new Date("2023-4-26 " + "20:30").getTime();
      hour = "迟到" + (vTime - eTime) / 60000 + "分钟";
      sTime;
    } else if (S != "" && S != "-" && E != "" && E != "-" && D == "综合部" && S > "13:00") {
      let sTime = new Date("2023-4-26 " + S).getTime();
      // let eTime = new Date("2023-4-26 " + E).getTime();
      let vTime = new Date("2023-4-26 " + "13:00").getTime();
      hour = "迟到" + (vTime - sTime) / 60000 + "分钟";
      // console.log(hour);
    } else if (S != "" && S != "-" && E != "" && E != "-" && D == "综合部" && S >= "12:00" && E >= "21:30") {
      // console.log(S, "上班");
      // console.log(E, "下班");
      let sTime = new Date("2023-4-26 " + S).getTime();
      let eTime = new Date("2023-4-26 " + E).getTime();
      let min = ((eTime - sTime) / 3600000).toFixed(2);
      let h = 0.5;
      let min2 = min - h;

      // console.log(min2, "减去时间");
      // console.log(min, "时间");
      if (min2 > 8) {
        hour = 8;
      } else if (min2 < 8) {
        const data = isSaveTime2(sTime, eTime, 8);
        hour = data.lackTime;
        console.log(data, "xxxxxxxxxxxx");
      }
      console.log("晚班客服");
    } else if (S != "" && S != "-" && E != "" && E != "-" && D != "运行工" && D != "安保" && S > "08:30") {
      // console.log(S, "上班3");
      // console.log(E, "下班3");
      let sTime = new Date("2023-4-26 " + S).getTime();
      // let eTime = new Date("2023-4-26 " + E).getTime();
      let vTime = new Date("2023-4-26 " + "8:30").getTime();
      hour = "迟到" + (vTime - sTime) / 60000 + "分钟";
      // console.log(hour);
    } else if (S != "" && S != "-" && E != "" && E != "-" && D == "安保" && S > "8:00" && E > "20:00") {
      // console.log(S, "上班3");
      // console.log(E, "下班3");
      let sTime = new Date("2023-4-26 " + S).getTime();
      // let eTime = new Date("2023-4-26 " + E).getTime();
      let vTime = new Date("2023-4-26 " + "8:00").getTime();
      hour = "迟到" + (vTime - sTime) / 60000 + "分钟";
      // console.log(hour);
    } else if (S != "" && S != "-" && E != "" && E != "-" && D != "运行工" && D != "安保") {
      // console.log(S, "上班");
      // console.log(E, "下班");
      let sTime = new Date("2023-4-26 " + S).getTime();
      let eTime = new Date("2023-4-26 " + E).getTime();
      let min = ((eTime - sTime) / 3600000).toFixed(2);
      let h = 1.5;
      let min2 = min - h;

      // console.log(min2, "减去时间");
      // console.log(min, "时间");
      if (min2 > 8) {
        hour = 8;
      } else if (min2 < 8) {
        const data = isSaveTime2(sTime, eTime, 8);
        hour = data.lackTime;
        console.log(data, "xxxxxxxxxxxx");
      }
      // console.log("白班");
    } else if (S != "" && S != "-" && E != "" && E != "-" && D == "安保" && S > "08:00" && E > "20:00") {
      // console.log(S, "上班3");
      // console.log(E, "下班3");
      let sTime = new Date("2023-4-26 " + S).getTime();
      // let eTime = new Date("2023-4-26 " + E).getTime();
      let vTime = new Date("2023-4-26 " + "8:00").getTime();
      hour = "迟到" + (vTime - sTime) / 60000 + "分钟";
      // console.log(hour);
    } else if (S != "" && S != "-" && E != "" && E != "-" && D == "安保" && S <= "08:00" && E >= "20:00") {
      console.log(S, "安保白班上班");
      console.log(E, "安保白班下班");
      let sTime = new Date("2023-4-26 " + S).getTime();
      let eTime = new Date("2023-4-26 " + E).getTime();
      const data = isSaveTime(sTime, eTime, 12);
      hour = data.lackTime;
    } else if (S != "-" && S != "" && E != "" && E != "-" && D == "安保" && S >= "08:00" && E <= "20:00") {
      console.log(S2, "安保晚班上班");
      console.log(E, "安保晚班下班");

      let sTime = new Date("2023-4-25 " + E).getTime(); // 上班
      let eTime = new Date("2023-4-26 " + S2).getTime(); // 下班
      // hour = ((eTime - sTime) / 3600000).toFixed(2) + "小时";
      const data = isSaveTime(sTime, eTime, 12);
      hour = data.lackTime;
    } else if (S == "-" && E != "" && E != "-" && D == "安保" && E <= "20:00") {
      console.log(S2, "安保晚班上班");
      console.log(E, "安保晚班下班");

      let sTime = new Date("2023-4-25 " + E).getTime(); // 上班
      let eTime = new Date("2023-4-26 " + S2).getTime(); // 下班
      // hour = ((eTime - sTime) / 3600000).toFixed(2) + "小时";
      const data = isSaveTime(sTime, eTime, 12);
      hour = data.lackTime;
    } else if (S != "" && S != "-" && E != "" && E != "-" && D == "安保" && E > "20:00") {
      // console.log(S, "上班3");
      // console.log(E, "下班3");
      let sTime = new Date("2023-4-26 " + S).getTime();
      // let eTime = new Date("2023-4-26 " + E).getTime();
      let vTime = new Date("2023-4-26 " + "20:00").getTime();
      hour = "迟到" + (vTime - sTime) / 60000 + "分钟";
      // console.log(hour);
    }
    arr.push(JSON.parse(JSON.stringify(hour)));

    out.push(JSON.parse(JSON.stringify(hour)));

    // hour.name = tableData.timeHeader[i];
    // arr.push(hour);
  }

  out.unshift(department);
  out.unshift(name);
  out.unshift(id);
  str.push(out);
  console.log(out);
  console.log(arr, "哈呼");
  console.log(tableData.timeHeader[1], "测试");
  return arr;
};

// 是否满足一天12小时工时   不满足 缺多少工时
// s 上班时间戳  e 下班时间戳  t 一天需要的上班时间
const isSaveTime = (s, e, t = 12) => {
  const data = {
    isSave: false, // 是否满足12小时
    lackTime: 0 // 缺少工时
  };
  console.log(s, e, "下班 -> 上班");
  const hour = ((e - s) / 3600000).toFixed(2);
  if (hour > t) {
    data.isSave = true;
    data.lackTime = 12;

    // data.lackTime = 12 + "小时";
  } else {
    data.isSave = false;
    data.lackTime = "缺" + ((t - hour) * 60).toFixed(2) + "分钟";
    console.log(t - hour, "缺分钟");
  }
  return data;
};

const isSaveTime2 = (s, e, t = 8) => {
  const data = {
    isSave: false, // 是否满足8小时
    lackTime: 0 // 缺少工时
  };
  const hour = ((e - s) / 3600000).toFixed(2);
  console.log(hour, "xuxu");
  if (hour > t) {
    data.isSave = true;
  } else {
    data.isSave = false;
    data.lackTime = "缺" + ((t - hour) * 60).toFixed(2) + "分钟";
    console.log(t - hour, "缺分钟");
  }
  return data;
};
let originalData = [];
let str = [];
let check = [];
let check2 = [];
// let xu = [];
// let xu2 = [];
const tableData = reactive({
  total: 0,
  pageSize: 20,
  current: 1,
  header: [],
  list: [],
  timeHeader: []
});
const sizeChange = e => {
  console.log(e);
  tableData.pageSize = e;
  tableData.current = 1;
  tableData.list = originalData.slice(0, e);
};

const currentChange = e => {
  console.log(e);
  tableData.current = e;
  let end = tableData.pageSize * e;
  tableData.list = originalData.slice(end - tableData.pageSize, end);
};
// 导出
async function exportExcel() {
  if (str == "") {
    ElNotification({
      title: "错误提示",
      message: h("i", { style: "color: red" }, "请展开每个员工的总工时即可导出!")
    });
  } else {
    let derive = [];
    for (let i in table) {
      const user = str.find(user => user["0"] === table[i].id);
      user.splice(3, 1);
      derive.push(user);
      console.log(user, "测试");
    }
    let newArry = derive.map(JSON.stringify);
    let setArry = [...new Set(newArry)];
    let uniqu = setArry.map(JSON.parse);
    console.log(uniqu, "导出二维数组");

    // const too = []; //定义数组
    // const too2 = [];
    // const too4 = [];
    const gauge = [
      "id",
      "部门",
      "姓名",
      "一日",
      "二日",
      "三日",
      "四日",
      "五日",
      "六日",
      "七日",
      "八日",
      "九日",
      "十日",
      "十一日",
      "十二日",
      "十三日",
      "十四日",
      "十五日",
      "十六日",
      "十七日",
      "十八日",
      "十九日",
      "二十日",
      "二十一日",
      "二十二日",
      "二十三日",
      "二十四日",
      "二十五日",
      "二十六日",
      "二十七日",
      "二十八日",
      "二十九日",
      "三十日",
      "三十一日"
    ];

    uniqu.unshift(gauge);
    console.log(uniqu, "数据");
    const data = XLSX.utils.json_to_sheet(uniqu); //此处tableData.value为表格的数据
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, data, "test-data"); //test-data为自定义的sheet表名
    XLSX.writeFile(wb, "test.xlsx"); //test.xlsx为自定义的文件名
  }
}

// 打开弹框在哪呢
// 导入
const handleChange = e => {
  console.log(e, "e");
  importfxx(e.raw);
};
const importfxx = async file => {
  let dataBinary = await readFile(file);
  let workBook = XLSX.read(dataBinary, { type: "binary", cellDates: true });
  let workSheet = workBook.Sheets[workBook.SheetNames[0]];
  const data = XLSX.utils.sheet_to_json(workSheet, { header: 1, defval: "" });

  const forList = data.slice(2, data.length);
  const header = data[1].slice(0, 12);
  // xu2 = header;
  const timeHeader = data[1].slice(12, data[1].length);
  let timeHeaderArr = [];
  console.log(data, "导入数据");
  timeHeader.forEach((v, i) => {
    timeHeaderArr.push({
      lable: v,
      prop: i + "prop"
    });
  });
  tableData.timeHeader = timeHeaderArr;
  tableData.header = header;

  for (let i = 0; i < forList.length; i++) {
    const v = forList[i];
    console.log(v, "测试");
    if (i % 2 == 0) {
      originalData.push({
        [header[0]]: v[0],
        [header[1]]: v[1],
        [header[2]]: v[2],
        [header[3]]: v[3],
        [header[4]]: v[4],
        [header[5]]: v[5],
        [header[6]]: v[6],
        [header[7]]: v[7],
        [header[8]]: v[8],
        [header[9]]: v[9],
        [header[10]]: v[10],
        [header[11]]: v[11],
        [header[12]]: v[12],
        work: [],
        work2: [],
        Gwork: v.slice(0, 3, v.length),
        Ywork: v.slice(12, v.length),
        Nwork: forList[i + 1].slice(12, v.length)
      });
      check.push(v[0]);
      check2.push(v[1]);
      check2.push(v[2]);
    }
  }
  originalData.forEach(v => {
    v.work[1] = { ...v.Ywork };
    v.work[2] = { ...v.Nwork };
    v.work[0] = { ...v.Gwork };
  });

  tableData.total = originalData.length;
  tableData.list = originalData.slice(0, tableData.pageSize);
  console.log(tableData.list);
  console.log(tableData.timeHeader);
  console.log(originalData, "xxx");
};
const readFile = file => {
  return new Promise(resolve => {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = ev => {
      resolve(ev.target.result);
    };
  });
};
</script>

<style scoped>
.tab-box {
  height: calc(100% - 50px);
  overflow: auto;
}
.tab-fotter {
  display: flex;
  align-items: center;
  height: 50px;
  padding-left: 20px;
}
.el-header {
  display: flex;
  align-items: center;
}
.button2 {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 32px;
  margin-bottom: 10px;
  margin-left: 10px;
  line-height: 1;
}
</style>
